<template>
  <div class="view-wrappers">
    <div class="view-inner-wrap">
      <div class="tabs-body">
        <div class="modify">
          <el-form :inline="true" :rules="rules" :model="formInline" ref="ruleForm" class="demo-form-inline">
            <el-form-item label="设置密码：" prop="password" :label-width="labelWidth">
              <el-input v-model="formInline.password" placeholder="请输入密码（6-20位数字字母组合）"></el-input>
            </el-form-item>
            <el-form-item label="店铺头像：" prop="shopIcon" :label-width="labelWidth" ref="shopIconRef">
              <ImageUploadMoreOldUrl :limit="1" :fileSize="20" @successImgOld="getShopIconImg"
                :value="formInline.shopIcon">
              </ImageUploadMoreOldUrl>
            </el-form-item>
            <el-form-item label="店铺名称：" prop="shopName" :label-width="labelWidth">
              <el-input v-model="formInline.shopName" placeholder="请输入店铺名称"></el-input>
            </el-form-item>
            <el-form-item label="店铺定位：" prop="locateAddress" :label-width="labelWidth">
              <span class="fontsize">{{ formInline.locateAddress }}</span>
              <el-input v-model="formInline.locateAddress" :disabled="true" v-show="false"></el-input>
              <span class="fontsize" @click="modelMsg = true"
                style="color: #1890ff; margin-left: 30px; cursor: pointer">点击定位地址</span>
            </el-form-item>
            <el-form-item label="详细地址：" prop="address" :label-width="labelWidth">
              <el-input v-model="formInline.address" placeholder="请输入详细地址"></el-input>
            </el-form-item>
            <!-- <el-form-item label="营业时间：" :label-width="labelWidth">
              <div class="time_box">
                <el-time-select v-model="formInline.startTime" placeholder="开始时间" :picker-options="{
                    start: '00:00',
                    step: '00:10',
                    end: '23:59',
                  }">
                </el-time-select>
                <span style="margin: 0 10px">-</span>
                <el-time-select v-model="formInline.endTime" placeholder="结束时间" :picker-options="{
                    start: '00:00',
                    step: '00:10',
                    end: '23:59',
                  }">
                </el-time-select>
              </div>
            </el-form-item> -->
            <el-form-item label="营业时间：" :label-width="labelWidth">
              <el-col :span="12">
                <el-form-item prop="startTime">
                  <el-time-select v-model="formInline.startTime" placeholder="开始时间" :picker-options="{
                    start: '00:00',
                    step: '00:10',
                    end: '23:59',
                  }">
                  </el-time-select>
                </el-form-item>
              </el-col>
              <el-col class="line" :span="1">-</el-col>
              <el-col :span="11">
                <el-form-item prop="endTime">
                  <el-time-select v-model="formInline.endTime" placeholder="结束时间" :picker-options="{
                    start: '00:00',
                    step: '00:10',
                    end: '23:59',
                  }">
                  </el-time-select>
                </el-form-item>
              </el-col>
            </el-form-item>
            <el-form-item label="每周营业日：" prop="weekTime" :label-width="labelWidth">
              <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选
              </el-checkbox>
              <el-input v-model="formInline.weekTime" placeholder="请输入店铺名称" v-show="false"></el-input>
              <div style="margin: 15px 0"></div>
              <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
                <el-checkbox v-for="dayItem in cities" :label="dayItem" :key="dayItem">{{
                  dayItem
                }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="店铺类型：" required prop="shopType" :label-width="labelWidth">
              <!-- el-input表单校验占位用，不显示 -->
              <el-input v-model="formInline.shopType" :disabled="true" v-show="false"></el-input>
              <!--  -->
              <el-cascader v-model="avalue" :options="typeLs" :show-all-levels="false" @change="handleChange">
              </el-cascader>
            </el-form-item>
            <el-form-item label="所属区域" required prop="province" :label-width="labelWidth">
              <!-- el-input表单校验占位用，不显示 -->
              <el-input v-model="formInline.province" :disabled="true" v-show="false"></el-input>
              <!--  -->
              <el-cascader :options="regionOptions" :props="{ value: 'id',label: 'label',children: 'children'}"
                @change="regionChange"></el-cascader>
            </el-form-item>
            <el-form-item label="店铺联系电话：" :label-width="labelWidth">
              <el-input v-model="formInline.phone" placeholder="请输入店铺联系电话"></el-input>
            </el-form-item>
            <el-form-item label="品牌介绍：" :label-width="labelWidth">
              <el-input type="textarea" v-model="formInline.introduce" placeholder="请输入" maxlength="300"
                show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="商家资质：" :label-width="labelWidth">
              <ImageUploadMoreOldUrl :limit="6" :fileSize="20" @successImgOld="getCompetencyImgList"
                :value="formInline.competencyImgList">
              </ImageUploadMoreOldUrl>
              <div>({{ formInline.competencyImgList.length }}/6)</div>
            </el-form-item>
            <el-form-item label="店铺图片：" :label-width="labelWidth">
              <!-- <div class="img_list">
                <div class="img_box" v-for="(item, index) in formInline.shopImgList" :key="index">
                  <div class="closeimg el-icon-circle-close" @click="detailImg(index)"></div>
                  <img :src="item" alt="" />
                </div>
                <el-upload v-if="formInline.shopImgList.length < 10" class="avatar-uploader2" :action="action"
                  :show-file-list="false" :on-success="listAvatarSuccess" :before-upload="beforeAvatarUpload"
                  :multiple="true" :limit="limit">
                  <i class="el-icon-plus" style="font-size: 28px"></i>
                </el-upload>
              </div> -->
              <ImageUploadMoreOldUrl :limit="10" :fileSize="20" @successImgOld="getShopImgList"
                :value="formInline.shopImgList">
              </ImageUploadMoreOldUrl>
              <div>({{ formInline.shopImgList.length }}/10)</div>
            </el-form-item>
            <el-form-item label="商家合同确认书：" prop="enterFile" :label-width="labelWidth" ref="enterFileRef">
              <!-- <ImageUploadMoreOldUrl :limit="1" :fileSize="20" :fileType="fileType" @successImgOld="getEnterFile"
                :value="formInline.enterFile">
              </ImageUploadMoreOldUrl> -->
              <el-upload class="upload-demo" :action="action" :on-preview="handlePreview" :on-remove="handleRemove"
                :before-remove="beforeRemove" multiple :limit="1" :on-exceed="handleExceed" :file-list="fileList" :on-success="handleUploadSuccess">
                <el-button size="small" type="primary">点击上传</el-button>
                <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
              </el-upload>
            </el-form-item>
            <el-form-item class="btn">
              <el-button style="margin-right: 30px" @click="previousStep">上一步</el-button>
              <!-- <el-button type="primary" @click="getSave">保存</el-button> -->
              <el-button type="primary" @click="getNext('ruleForm')">下一步</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <img-detail-dialog v-if="ImgDetailDialog" :id="id" :imgUrl="urlData" :visible.sync="ImgDetailDialog" />
    <el-dialog title="选择定位" :visible.sync="modelMsg">
      <div class="msgDiv">
        <el-autocomplete style="width: 80%; margin-right: 10px" class="inline-input" v-model="address"
          :fetch-suggestions="watchInput" placeholder="请输入内容" :trigger-on-focus="false" @select="handleSelect">
        </el-autocomplete>
        <div id="container" style="margin-top: 20px"></div>
        <div class="dialog_bottom">
          <el-button style="margin-right: 60px" @click="modelMsg = false">取消</el-button>
          <el-button type="primary" @click="determine">确定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {
    shopTypeTree,
    addHlb,
    getCity
  } from "@/api/clientManagement"; 
  import ImageUploadMoreOldUrl from "@/components/ImageUploadMoreOldUrl"
  export default {
    name: "shopDetail",
    components: {
      ImageUploadMoreOldUrl
    },
    provide() {
      const {
        id
      } = this.$route.query;
      return {
        id: id,
      };
    },
    data() {
      var checkWeekTime = (rule, value, callback) => {
        console.log('value是', value)
        if (!value) {
          return callback(new Error('请选择每周营业日'));
        } else {
          callback();
        }
      };
      var checkShopType = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请选择店铺类型'));
        } else {
          callback();
        }
      };
      var checkProvince = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请选择所属区域'));
        } else {
          callback();
        }
      };
      return {
        labelWidth: '140px',
        inputWidth: '300px',
        avalue: [],
        fileList: [],
        ImgDetailDialog: false,
        modelMsg: false, //显示模态框
        address: "", //输入的地址
        mapList: [], //用来存搜索到的所有地址
        mapVal: "", //创建的地图，赋值用
        id: "",
        fileType: [],
        action: process.env.VUE_APP_BASE_API + "/common/v1/uploadFile",
        loading: false,
        formInline: {
          password: '', //密码
          shopIcon: "", //店铺头像
          shopName: "", //店铺名称
          shopType: "", //店铺子类型
          shopTypeParent: "", //店铺父类型
          shopTypeName: "", //店铺子类型名称
          shopLnt: "", //店铺经度
          shopLat: "", //店铺纬度
          address: "", //详细地址
          locateAddress: "", //定位地址
          status: "", //店铺状态 1 用户端展示  2 用户端不展示  字典：merchant_shop_spurious_status
          shopImgList: [], //店铺图片
          competencyImgList: [], //资质图片
          startTime: "", //开始时间
          endTime: "", //结束时间
          weekTime: "", //每周营业日
          phone: "", //店铺联系电话
          introduce: "", //品牌介绍
          province: '', //省
          city: '', //市
          area: '', //区
          enterFile: '', //商家合同确认书
        },
        rules: {
          shopIcon: [{
            required: true,
            message: '请上传店铺头像',
            trigger: 'change'
          }],
          shopName: [{
            required: true,
            message: '请输入店铺名称',
            trigger: ['blur', 'change']
          }],
          address: [{
            required: true,
            message: '请输入详细地址',
            trigger: ['blur', 'change']
          }],
          shopType: [{
            required: true,
            message: '请选择店铺类型',
            trigger: ['blur', 'change']
          }],
          //   startTime: [{
          //     required: true,
          //     message: '请选择开始时间',
          //     trigger: ['blur', 'change']
          //   }],
          //   endTime: [{
          //     required: true,
          //     message: '请选择结束时间',
          //     trigger: ['blur', 'change']
          //   }],
          //   weekTime: [{
          //     validator: checkWeekTime,
          //     trigger: 'change'
          //   }],
          password: [{
            required: true,
            message: '请输入密码（6-20位数字字母组合）',
            trigger: ['blur', 'change']
          }],
          locateAddress: [{
            required: true,
            message: '请选择店铺定位',
            trigger: ['blur', 'change']
          }],
          shopType: [{
            validator: checkShopType,
            trigger: 'change'
          }],
          province: [{
            validator: checkProvince,
            trigger: 'change'
          }],
          enterFile: [{
            required: true,
            message: '请上传商家合同确认书',
            trigger: 'change'
          }],
        },
        typeLs: [],
        regionOptions: [], //城市数组
        value: true,
        checkAll: false,
        checkedCities: [],
        cities: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
        isIndeterminate: false,
        pathType: '',
      };
    },
    watch: {
      //监听模态框是否显示,显示就执行初始化地图方法
      modelMsg(newVal, oldVal) {
        console.log(newVal);
        if (newVal == true) {
          this.initMap(20.049818248, 110.354108124);
        }
      },
    },
    created() {
      this.getTypels();
      this.getCity();
      console.log('aaaa', this.$route.query.pathType)
      this.pathType = this.$route.query.pathType
    },
    mounted() {
      let query = this.$route.query;
    },
    methods: {
      getShopIconImg(e) { //店铺头像
        console.log(e)
        this.formInline.shopIcon = e
        this.$refs['shopIconRef'].clearValidate();
      },
      cancel() {
        //取消
        this.$router.go(-1);
      },
      handleCheckAllChange(val) {
        this.checkedCities = val ? this.cities : [];
        this.isIndeterminate = false;
        console.log(val);
        console.log(this.checkedCities);
        if (val == true) {
          this.formInline.weekTime = "周一至周日";
        } else {
          this.formInline.weekTime = "";
        }
        console.log(this.formInline.weekTime);
      },
      handleCheckedCitiesChange(value) {
        console.log(value)
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.cities.length;
        this.isIndeterminate =
          checkedCount > 0 && checkedCount < this.cities.length;
        console.log(this.checkedCities);
        let dataone = this.checkedCities.join("、");
        console.log(dataone);
        if (dataone == "") {
          this.formInline.weekTime = "";
        } else if (dataone == "周一、周二、周三、周四、周五、周六、周日") {
          this.formInline.weekTime = "周一至周日";
        } else {
          this.formInline.weekTime = dataone;
        }
        console.log(this.formInline.weekTime);
      },
      handleSelect(item) { //地图搜索
        console.log(item);
        this.initMap(item.location.lat, item.location.lng);
        this.formInline.shopLnt = item.location.lng;
        this.formInline.shopLat = item.location.lat;
      },
      determine() { ////地图搜索确定
        console.log(this.address);
        this.formInline.locateAddress = this.address;
        this.modelMsg = false;
      },
      watchInput(queryString, cb) {
        console.log(queryString);
        const KEY = "IFRBZ-GZ2CQ-YHW5J-GSUGE-RC7VS-JBBWN";
        let url = "https://apis.map.qq.com/ws/place/v1/suggestion";
        let keyword = queryString; //传入的关键词
        this.$jsonp(url, {
            key: KEY,
            region: "全国",
            keyword: keyword,
            output: "jsonp",
          })
          .then((res) => {
            let opt = [];
            res.data.forEach((res) => {
              let opt1 = {
                value: res.title + "-" + res.address,
                location: res.location,
              };
              opt.push(opt1);
            });
            this.mapList = opt;
            console.log(this.mapList);
            // 调用 callback 返回建议列表的数据
            cb(this.mapList);
          })
          .catch((err) => {
            console.log(err);
          });
      },
      initMap(lat, lng) {
        //如果地图存在，就销毁，下面会重新创建一个
        if (this.mapVal) {
          this.mapVal.destroy();
        }
        //定义地图中心点坐标
        //this.$nextTick是等Dom加载完再执行
        this.$nextTick(() => {
          var center = new window.TMap.LatLng(lat, lng);
          //定义map变量，调用 TMap.Map() 构造函数创建地图
          this.mapVal = new TMap.Map(document.getElementById("container"), {
            center: center, //设置地图中心点坐标
            zoom: 17.2, //设置地图缩放级别
            pitch: 43.5, //设置俯仰角
            rotation: 45, //设置地图旋转角度
            viewMode: "2D",
            mapStyleId: "style1", //个性化样式
          });
          //初始化marker
          var marker = new TMap.MultiMarker({
            id: "marker-layer", //图层id
            map: this.mapVal,
            styles: {
              //点标注的相关样式
              marker: new TMap.MarkerStyle({
                width: 25,
                height: 35,
                anchor: {
                  x: 16,
                  y: 32,
                },
                src: "https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/markerDefault.png",
              }),
            },
            geometries: [{
              //点标注数据数组
              id: "demo",
              styleId: "marker",
              position: new TMap.LatLng(lat, lng),
              properties: {
                title: "marker",
              },
            }, ],
          });
        });
      },
      regionChange(value) { //城市区域选择
        this.formInline.province = value[0];
        this.formInline.city = value[1];
        this.formInline.area = value[2];
      },
      getCity() { //查询城市数据
        const params = {};
        getCity(params)
          .then((res) => {
            this.regionOptions = res.result;
            this.regionOptions.forEach((item) => {
              item.children.forEach((items) => {
                items.children.forEach((itemss) => {
                  if (itemss.children.length == 0) {
                    itemss.children = null
                  }
                })
              })
            })
          })
          .finally(() => {});
      },
      // 获取店铺类型
      getTypels() {
        //shopTypeTree
        this.loading = true;
        shopTypeTree()
          .then((res) => {
            let ls = [];
            console.log("res.result+++", res.result);
            ls = this.getTreeData(res.result);
            // console.log(this.typeLs)
            let ls1 = ls.map((item) => {
              item.value = item.id;
              item.children.map((items) => {
                items.value = items.id;
              });
              return item;
            });
            this.typeLs = ls1;
          })
          .finally(() => {
            this.loading = false;
          });
      },
      handleChange(value) { //店铺类型选择
        console.log(this.avalue);
        let _this = this;
        console.log("value+++++++++++++", value[1], value);
        _this.formInline.shopType = value[1];
        _this.formInline.shopTypeParent = value[0]
        console.log(this.typeLs)
        this.typeLs.forEach((item) => {
          item.children.forEach((nav) => {
            if (nav.id == _this.formInline.shopType) {
              _this.formInline.shopTypeName = nav.label
            }
          })
        })
      },
      getTreeData(data) {
        // 循环遍历json数据
        for (var i = 0; i < data.length; i++) {
          if (data[i].children.length < 1) {
            // children若为空数组，则将children设为undefined
            // data[i].children=undefined;
            delete data[i].children;
          } else {
            // children若不为空数组，则继续 递归调用 本方法
            this.getTreeData(data[i].children);
          }
        }
        return data;
      },
      getCompetencyImgList(e) { //店铺资质图片
        console.log('e', e)
        // var reg1 = new RegExp("https://bee.xiaodaiyan.com", "g"); // 加'g'，删除字符串里所有的"a"
        // e = e.replace(reg1, "");
        if (e != '') {
          this.formInline.competencyImgList = e.split(",")
        } else {
          this.formInline.competencyImgList = []
        }
      },
      getShopImgList(e) { //店铺图片上传
        console.log('e', e)
        if (e != '') {
          this.formInline.shopImgList = e.split(",")
        } else {
          this.formInline.shopImgList = []
        }
      },
      getEnterFile(e) { //合同确认文件
        console.log(e)
        this.formInline.enterFile = e
        this.$refs['enterFileRef'].clearValidate();
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
        this.formInline.enterFile = ''
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      handleUploadSuccess(res){
          this.formInline.enterFile = res.result.url
          this.$refs['enterFileRef'].clearValidate();
      },
      //上一步
      previousStep() {
        this.$emit('previousStep')
      },
      /** 下一步 */
      getNext(formName) {
        //  return
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$emit('successFrom', this.formInline)
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
    },
  };

</script>
<style lang="scss" scoped>
  .merchantsId {
    color: #303133;
    font-size: 15px;
    margin-bottom: 16px;
  }

  .tabs-body {
    background-color: #fff;
    padding: 20px 0;
  }

  .text_ls {
    display: flex;
    align-items: center;
    min-height: 36px;
    line-height: 36px;
    margin: 5px 0;
  }

  .ls_left {
    font-size: 15px;
    color: #333333;
    width: 200px;
    text-align: right;
  }

  .ls_right {
    font-size: 15px;
    color: #333333;
    display: flex;
    align-items: center;
  }

  .ls_bottom {
    padding-top: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    box-sizing: border-box;
  }

  .avatar-uploader {
    border: 1px dashed #d9d9d9;
  }

  .avatar-uploader .el-upload {
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }

  .avatar {
    width: 148px;
    height: 148px;
    display: block;
  }

  .el-form-item {
    display: flex;
  }

  .el-input {
    width: 300px;
  }

  .modify ::v-deep.el-textarea__inner {
    width: 500px !important;
    height: 90px;
  }

  .btn {
    display: flex;
    justify-content: center;
  }

  .fontsize {
    font-size: 15px;
  }

  .modify {
    padding: 10px 0px;
  }

  .dialog_bottom {
    margin-top: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
  }

  .rig_img {
    width: 40px;
    height: 40px;
    margin-right: 10px;
    border-radius: 4px;
  }

  .avatar-uploader2 {
    width: 148px;
    height: 148px;
    text-align: center;
    line-height: 148px;
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
    margin-bottom: 12px;
  }

  .closeimg {
    position: absolute;
    top: 0px;
    right: 0;
    z-index: 99;
    font-size: 28px;
    cursor: pointer;
    background: #4e4e4e;
  }

  .img_box {
    width: 148px;
    height: 148px;
    margin-right: 12px;
    margin-bottom: 12px;
    border-radius: 4px;
    position: relative;
  }

  .img_list {
    display: flex;
    align-items: center;
    flex: 1;
    flex-wrap: wrap;
  }

  .img_list img {
    border-radius: 4px;
    width: 100%;
    height: 100%;
  }

  .img_list::v-deep .avatar-uploader2 .el-upload {
    width: 100% !important;
  }

  .line {
    padding-left: 4px;
  }

</style>
